package BUS;

import DTO.TableMailDataDTO;
import DTO.MailStructureDTO;
import java.awt.Image;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Vector;
import javax.mail.MessagingException;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import sun.security.util.PropertyExpander.ExpandException;
import java.lang.Object;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.TableColumnModel;
import DTO.*;
import DAO.*;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Icon;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import sun.awt.shell.ShellFolder;


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author NxSiHMr0D
 */
public class MailFunctionBUS {

    TableMailDataDTO _model;
     ExcuteMailDAO _mailTmp;
    public MailFunctionBUS() throws ParserConfigurationException, SAXException, IOException, Exception {
        // _model = new DefaultTableModel(data, columnNames);
        _model = new TableMailDataDTO();
        _mailTmp = new ExcuteMailDAO();

    }
    /**
     * get List mail by ID
     * @param idFolder : ID folder ( from database)
     * @return
     * @throws javax.xml.parsers.ParserConfigurationException
     * @throws org.xml.sax.SAXException
     * @throws java.io.IOException
     * @throws java.lang.Exception
     */
    public ArrayList<MailStructureDTO>  getListMail(int idFolder) throws ParserConfigurationException, SAXException, IOException, Exception
    {
        ExcuteMailDAO excMail = new ExcuteMailDAO();
        ArrayList<MailStructureDTO> tmplstMail = excMail.getMailFromDatabase(new AccountMailDTO());
        ArrayList<MailStructureDTO> lstMail = new ArrayList<MailStructureDTO>();
        for ( MailStructureDTO am : tmplstMail){
            if ( idFolder == am.getMailIn())
                lstMail.add(am);
        }
        return lstMail;
    }
    /**
     * delete exist mail from database
     * @param mail
     * @throws java.sql.SQLException
     * @throws java.lang.Exception
     */
    public void deleteMail(MailStructureDTO mail) throws SQLException, Exception{
        _mailTmp.deleteMail(mail);
    }
    /**
     * show mail to GUI ( table)
     * @param tmp
     * @throws java.lang.Exception
     */
    public void showMails(JTable tmp) throws Exception {
        //ExcuteMailDAO mailTmp = new ExcuteMailDAO();
        AccountMailDTO acc = new AccountMailDTO();
        try {
            _mailTmp.diconnectServer();
            _mailTmp.connectServer();
            showMails(tmp, "INBOX", _mailTmp,-1);
        } catch (Exception ex) {

            throw new Exception("can not connect to server mail" + ex.getMessage());
        //return;
        }
    }
    /**
     * show mail to GUI
     * @param tmp
     * @param idFolder
     * @throws java.lang.Exception
     */
     public void showMails(JTable tmp,int idFolder) throws Exception {
        //ExcuteMailDAO mailTmp = new ExcuteMailDAO();
        AccountMailDTO acc = new AccountMailDTO();
        try {
            //_mailTmp.diconnectServer();
            //_mailTmp.connectServer();
            showMails(tmp, "INBOX", _mailTmp,idFolder);
        } catch (Exception ex) {

            throw new Exception("can not connect to server mail" + ex.getMessage());
        //return;
        }
    }
    //@SuppressWarnings("empty-statement")
/**
 * get list attach file
 * @param rows
 * @param tbListMail
 * @return
 * @throws java.io.FileNotFoundException
 */
    public ArrayList<File> showAttachFile(int rows, JTable tbListMail) throws FileNotFoundException {
        try {
            MailStructureDTO mailAttach = ((TableMailDataDTO) tbListMail.getModel()).getRealData().get(rows);

            ArrayList<File> attachFile = mailAttach.getAttachFiles();
            return attachFile;
        } catch (Exception ex) {
            return null;
        }


    }
    /**
     * set mark for mail
     * @param rows
     * @param tbListMail
     * @param Mask
     * @throws java.sql.SQLException
     */
    public void setMaskMail(int rows, JTable tbListMail,int Mask) throws SQLException{
        MailStructureDTO mail = ((TableMailDataDTO) tbListMail.getModel()).getRealData().get(rows);
        int IDMail = mail.getIdMail();
        _mailTmp.setMaskMail(IDMail, Mask);
        _model.setTypeMail(Mask, rows);
    }
    /**
     * save attach File to computer.
     * @param rows
     * @param tbListMail
     * @param filenameAttach
     * @param dectination
     * @throws java.lang.Exception
     */
    public void saveAttachFile(int rows, JTable tbListMail, String filenameAttach, String dectination) throws Exception {
        MailStructureDTO mailAttach = ((TableMailDataDTO) tbListMail.getModel()).getRealData().get(rows);
       
       // mailTmp.connectServer();
        _mailTmp.saveAttachFile(mailAttach, filenameAttach, dectination);
    }
    /**
     * get content of mail
     * @param txtContentMail
     * @param tbListMail
     * @param rows
     * @return
     */
    public String getContentMail(JEditorPane txtContentMail ,JTable tbListMail, int rows) {

        MailStructureDTO mail = ((TableMailDataDTO) tbListMail.getModel()).getRealData().get(rows);

        String html = mail.getContentHTML();
        if ( !html.equals("")){
            txtContentMail.setContentType("text/html");
            return html;
        }

            
        txtContentMail.setContentType("text");

        return mail.getContent();
    }
    /**
     * get mail selected by user.
     * @param tbListMail
     * @param rows
     * @return
     */
    public MailStructureDTO getMail(JTable tbListMail, int rows){
        MailStructureDTO mail = ((TableMailDataDTO) tbListMail.getModel()).getRealData().get(rows);
        return mail;
    }
    /**
     * save a mail , mail can be read or not read
     * @param mail
     * @param mailIn
     * @param typeMail
     */
    public static void saveMail(MailStructureDTO mail, ConstantValue.MailIn mailIn, ConstantValue.TypeMail typeMail) throws SQLException {
        //create object mailDTO to save info

        MailDTO mailDTO = new MailDTO();
        AccountMailBUS acc = new AccountMailBUS();
        int idSender = acc.getMailFromAddress(mail.getSender()).getId();
        mailDTO.set_idSender(idSender);
        mailDTO.set_content(mail.getContent());
        mailDTO.set_subject(mail.getTitle());
        mailDTO.set_mailIn(mailIn.value());
        mailDTO.set_typeMail(typeMail.value());
        mailDTO.set_datetimeSent(mail.getDateSend());
        //call procedure to execute save info mail
        int newID = BUS.MailBUS.addMail(mailDTO);
        //save table Receiver
        //save file attached
        FileAttachedDTO fileAttached = new FileAttachedDTO();
        fileAttached.set_idMail(newID);
        for (File file : mail.getAttachFiles()) {
            fileAttached.set_pathFileAttached(file.getPath());
            FileAttachedBUS.add(fileAttached);
        }
    //

    }
/**
 * show mail to GUI
 * @param tmp
 * @param folder
 * @param excMail
 * @param idFoder
 * @throws javax.mail.MessagingException
 * @throws java.lang.Exception
 */
    public void showMails(JTable tmp, String folder, ExcuteMailDAO excMail,int idFoder) throws MessagingException, Exception {

//        tmp.setModel(_model);
//        MailStructureDTO mail= new MailStructureDTO();
//        mail.setDateSend("11/08/2008");
//        mail.setSender("Tester1");
//        mail.setIsAttachment(true);
//        mail.setTitle("TestMail1");
        _model = new TableMailDataDTO();
        TableColumnModel cm = new DefaultTableColumnModel() {

            boolean first = true;

            @Override
            public void addColumn(TableColumn tc) {
                tc.setMinWidth(30);

                if (first) {
                    first = false;
                    tc.setMaxWidth(90);
                    tc.setPreferredWidth(30);
                    tc.setWidth(30);
                    super.addColumn(tc);
                    return;
                }
                // Drop the first column . . . that'll be the row header

                super.addColumn(tc);
            }
        };
        tmp.setColumnModel(cm);
        tmp.setModel(_model);
        TableColumn hdr = tmp.getTableHeader().getColumnModel().getColumn(4);
        hdr.setPreferredWidth(30);
        hdr.setMaxWidth(90);
        hdr.setMinWidth(30);
        hdr.setWidth(30);
        TableColumnModel cModel = tmp.getColumnModel();
        cModel.getColumn(4).setMaxWidth(90);
        cModel.getColumn(4).setMinWidth(30);
        cModel.getColumn(4).setWidth(30);
        cModel.getColumn(4).setPreferredWidth(30);


        //ArrayList<MailStructureDTO> lstMail = excMail.getMailFormFolder(folder);
        ArrayList<MailStructureDTO> lstMail = excMail.getMailFromDatabase(new AccountMailDTO());
        if ( idFoder ==-1){
            ArrayList<MailStructureDTO> mailServerNew = excMail.getMailFormFolder(folder);

            for (MailStructureDTO mail : mailServerNew) {
                lstMail.add(mail);
            }
        }
          
        for (MailStructureDTO mail : lstMail) {
            if (idFoder == -1)
                _model.addRow(mail);
            else
                if (mail.getMailIn() == idFoder){
                    _model.addRow(mail);
                }

        }



    }
    /**
     * show mail to GUI ( only search mail).
     * @param tmp
     * @param lstMailSearch
     */
    public void showSearchMails(JTable tmp, ArrayList<MailStructureDTO> lstMailSearch){
         _model = new TableMailDataDTO();
        TableColumnModel cm = new DefaultTableColumnModel() {

            boolean first = true;

            @Override
            public void addColumn(TableColumn tc) {
                tc.setMinWidth(30);

                if (first) {
                    first = false;
                    tc.setMaxWidth(90);
                    tc.setPreferredWidth(30);
                    tc.setWidth(30);
                    super.addColumn(tc);
                    return;
                }
                // Drop the first column . . . that'll be the row header

                super.addColumn(tc);
            }
        };
        tmp.setColumnModel(cm);
        tmp.setModel(_model);
        TableColumn hdr = tmp.getTableHeader().getColumnModel().getColumn(4);
        hdr.setPreferredWidth(30);
        hdr.setMaxWidth(90);
        hdr.setMinWidth(30);
        hdr.setWidth(30);
        TableColumnModel cModel = tmp.getColumnModel();
        cModel.getColumn(4).setMaxWidth(90);
        cModel.getColumn(4).setMinWidth(30);
        cModel.getColumn(4).setWidth(30);
        cModel.getColumn(4).setPreferredWidth(30);
         for (MailStructureDTO mail : lstMailSearch) {
            
                    _model.addRow(mail);
        }


    }
    /**
     * check mail is or isn't Format Address.
     * @param mail
     * @return
     */
    public static boolean checkIsEmailAddress(String mail) {
        int index = mail.indexOf("@");
        if (index == -1 || index == 0 || index == mail.length() - 1) {
            return false;
        }
        return true;
    }
    /**
     * save mail 2 database.
     * @param tbListMail
     * @throws java.sql.SQLException
     * @throws java.io.UnsupportedEncodingException
     */
    public void saveMail2Database(JTable tbListMail) throws SQLException, UnsupportedEncodingException {
        int rows = 0;
        int count = tbListMail.getModel().getRowCount();
        ArrayList<MailStructureDTO> lstTmpMail = new ArrayList<MailStructureDTO>();
        for (rows = 0; rows < count; rows++) {
            MailStructureDTO mailAttach = ((TableMailDataDTO) tbListMail.getModel()).getRealData().get(rows);
            if ( mailAttach != null)
                lstTmpMail.add(mailAttach);
        }
        _mailTmp.saveMail2DataBase(lstTmpMail);
    }
    /**
     * send mail to receiver.
     * @param mailServer
     * @param toReceiver
     * @param ccReceiver
     * @param bccReceiver
     * @param mail
     * @return
     * @throws java.io.IOException
     */
    public static int sendMail(String mailServer, ArrayList<String> toReceiver, ArrayList<String> ccReceiver, ArrayList<String> bccReceiver, MailStructureDTO mail) throws IOException {
        String errors = "";
        if (mail.getSender() == null) {
            errors += "     Sender is not found\n";
        }
        if (checkIsEmailAddress(mail.getSender()) == false) {
            errors += "     Sender is not correct format\n";
        }
        if (mail.getTitle() == null) {
            errors += "     Subject is not null";
        }
        if (mail.getContent() == null) {
            errors += "     Content is not null";
        }
        if (errors.length() != 0) {
            JOptionPane.showMessageDialog(null, "Have some problems while sending mail\n" + errors);
        }
        try {
            ExcuteMailDAO.sendMail(mailServer, toReceiver, ccReceiver, bccReceiver, mail);

        } catch (MessagingException ex) {
            JOptionPane.showMessageDialog(null, ex.toString());
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, ex.toString());
        }
        return 0;
    }
//   class TableMailDataDTO extends AbstractTableModel {
//        private String[] _columnNames = {"Đánh dấu","Chủ đề","Người gởi","Ngày gởi","Đính kèm"};
//        private ArrayList<Object> _data;
//        private ArrayList<MailStructureDTO> _realData;
//
//
//        public TableMailDataDTO(){
//            _data = new ArrayList<Object>();
//            _realData = new ArrayList<MailStructureDTO>();
//
//        }
//
//        public void addRow(MailStructureDTO mail){
//
//            ImageIcon icon = new ImageIcon();
//            ImageIcon icon2 = new ImageIcon();
//            //if ( mail.getIsFlag() == true)
//                icon2 = new ImageIcon("Image/flag-blue.png");
//            if ( mail.getIsAttachment() == true)
//                icon = new ImageIcon("Image/Pin.png");
//            Object value[]={icon2,mail.getTitle(),mail.getSender(),mail.getDateSend() ,icon};
//
//            try{
//                _data.add(value);
//                _realData.add(mail);
//                getRealData().add(mail);
//            }catch(Exception ex){
//                JOptionPane.showMessageDialog(null, ex);
//            }
//
//            this.fireTableDataChanged();
//
//        }
//        public int getRowCount() {
//            //throw new UnsupportedOperationException("Not supported yet.");
//            return _data.size();
//        }
//
//        public int getColumnCount() {
//            //throw new UnsupportedOperationException("Not supported yet.");
//             return _columnNames.length;
//        }
//        @Override
//         public String getColumnName(int col) {
//            return _columnNames[col];
//        }
//         /*
//         * JTable uses this method to determine the default renderer/
//         * editor for each cell.  If we didn't implement this method,
//         * then the last column would contain text ("true"/"false"),
//         * rather than a check box.
//         */
//        @Override
//        public Class getColumnClass(int c) {
//            return getValueAt(0, c).getClass();
//        }
//
//        /*
//         * Don't need to implement this method unless your table's
//         * editable.
//         */
//        @Override
//        public boolean isCellEditable(int row, int col) {
//            //Note that the data/cell address is constant,
//            //no matter where the cell appears onscreen.
////            if (col < 2) {
////                return false;
////            } else {
////                return true;
////            }
//            return false;
//        }
//
//        /*
//         * Don't need to implement this method unless your table's
//         * data can change.
//         */
//        @Override
//        public void setValueAt(Object value, int row, int col) {
//            _data.add(value);
//            fireTableCellUpdated(row, col);
//
//        }
//        public Object getValueAt(int rowIndex, int columnIndex) {
//            //throw new UnsupportedOperationException("Not supported yet.");
//             return ((Object[])(_data.get(rowIndex)))[columnIndex];
//        }
//
//        /**
//         * @return the _realData
//         */
//        public ArrayList<MailStructureDTO> getRealData() {
//            return _realData;
//        }
//
//        /**
//         * @param realData the _realData to set
//         */
//        public void setRealData(ArrayList<MailStructureDTO> realData) {
//            this._realData = realData;
//        }
//
//
//
//    }
}
